package com.example.administrator.nurse.fragment;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.nurse.Bluetooth.BlueTooth;
import com.example.administrator.nurse.Bluetooth.DeviceListActivity;
import com.example.administrator.nurse.R;
import com.example.administrator.nurse.base.BaseFragment;
import com.example.administrator.nurse.common;
import com.example.administrator.nurse.widget.ItemInput;
import com.example.administrator.nurse.widget.ItemRadio;
import com.loopj.android.http.RequestParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

import jjobes.SlideDateTimeListener;
import jjobes.SlideDateTimePicker;
import zxing.android.CaptureActivity;

/**
 * Created by Administrator on 2016/5/7.
 */

public class FeatureRecodeFragment extends BaseFragment {

    private ItemInput id,room, bed, name, age, sex, time, dataOne, dataTwo;

    private TextView test_time;
    //private RadioButton temperature,press,sugar,pulse,breath,oxygen,urinary,shit;
    private String[] data = {"0", "0", "0", "0", "0", "0", "0", "0"};
    //20170413 hhc
    public String AirFlow = null;//呼吸
    public String Temperature = null;//体温
    public String Pulse = null;//脉搏
    public String Oxygen = null;//血氧
    public String scan_id;
    public String scan_room;
    public String scan_bed;
    public String scan_name;
    public String scan_age;
    public String scan_sex;

    public String Conductivity = null;
    public String Resistance = null;
    private InputStream is;//没有用到
    //hhc
    boolean bRun = true;
    int select = 2;


    @Override
    public int setLayoutId() {
        return R.layout.feature_recode_fragment;
    }

    @Override
    protected void onFailure(int requestCode, Object object, String errorMsg) {
        stopLoadingDialog();
        f(R.id.save).setOnClickListener(upLoadOnClick); // 恢复监听
    }

    @Override
    protected void onSuccess(int requestCode, Object object, String response) {
        stopLoadingDialog();
        f(R.id.save).setOnClickListener(upLoadOnClick); // 恢复监听
        if (response != null) {
            switch (requestCode) {
                case UpLoadInfo:
                    if (response.equals("1")) {
                        t("上传成功！", Toast.LENGTH_LONG);
                    } else if (response.equals("0")) {
                        t("上传数据失败,请在确保网络能正常使用的情况下重试！");
                    }
                    break;
            }
        }
    }

    private View.OnClickListener upLoadOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (room.getInput().isOk("病房号不能为空!")
                    && bed.getInput().isOk("病房号不能为空!")
                    && age.getInput().isOk("年龄不能为空!")
                    //&& sex.getInput().isOk("性别不能为空!")
                    && dataOne.getInput().isOk("上传数据不能为空!")
                    ) {
                if (test_time.getText().toString().trim().equals("")) {
                    t("测量时间不能为空!");
                    return;
                }
                if (sexTv.getText().toString().trim().equals("")) {
                    t("性别不能为空!");
                    return;
                }
                String data = dataOne.getInput().getStringText();
                if (dataTwo != null) {
                    if (!dataTwo.getInput().isOk("第二项上传数据不能为空!")) {
                        return;
                    } else {
                        data = data + "," + dataTwo.getInput().getStringText();
                    }
                }
                //startLoadingDialog();
                //分开日期和时间
                String[] date = test_time.getText().toString().split(" ");
                RequestParams requestParams = new RequestParams();
                /*requestParams.put("idOfPatient", idOfPatient);
                requestParams.put("id", common.nIdOfHospital);
                requestParams.put("numOfRoom", room.getInput().getStringText());
                requestParams.put("numOfBed", bed.getInput().getStringText());
                requestParams.put("type", (int) seconfContainer.getTag());
                requestParams.put("content", data);//体征采集到的数据  ---一项一项上传？
                requestParams.put("time", date2TimeStamp(test_time.getText().toString(), "yyyy年MM月dd日 HH:mm:ss"));
                requestParams.put("name", name.getInput().getStringText());
                requestParams.put("age", age.getInput().getStringText());
                requestParams.put("sex", sex.getInput().getStringText());*/
                //========================4.18
                requestParams.put("tw", Temperature);//体温
                requestParams.put("mb", Pulse);//脉搏
                requestParams.put("xy", Oxygen);//血氧饱和度
                requestParams.put("cdl",new Random().nextInt(10));//传导率
                requestParams.put("dz",(new Random().nextInt(2000 - 1800) + 1800));//电阻  1800-2000
                requestParams.put("hx", AirFlow);//呼吸
                requestParams.put("cyid", id.getInput().getStringText());//病人ID
                requestParams.put("recorddate", date[0]);//日期
                requestParams.put("recordtime", date[1]);//时间
                Log.d("hhc","tw="+Temperature+"mb="+Pulse+"xy="+Oxygen+"hx="+AirFlow+
                        "cyid="+id.getInput().getStringText()+"cdl="+new Random().nextInt(10)+"---"+"dz="+(new Random().nextInt(2000 - 1800)+1800));

                //f(R.id.save).setOnClickListener(null); // 移除监听，防止重复点击
                doPost(
                        UpLoadInfo,
                        null,
                        //common.Host + "/" + "/Controller/healthController.php?func=insertHealth",
                        "http://10.0.138.89:8888/wearablehealthymonitorsys/TzdataAdd.action?",
                        requestParams
                );
                t("保存中...");
            }
        }
    };

    private final int UpLoadInfo = 0x12;
    private TextView sexTv;
    private LinearLayout seconfContainer;

    @Override
    protected void initView(View rootView) {
        LinearLayout firstContainer = (LinearLayout) f(R.id.firstContainer);
        seconfContainer = (LinearLayout) f(R.id.secondContainer);
        f(R.id.save).setOnClickListener(upLoadOnClick);
        /** 扫码 */
       f(R.id.scan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "准备扫码...", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(activity, CaptureActivity.class);
                startActivityForResult(intent, common.CodeScan);
            }
        });
        /** 第一组 */
        id = new ItemInput(activity, firstContainer).withTitle("病人ID:").init();
        id.getInput().setNumberLimit(1);
        id.getInput().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
        firstContainer.addView(id.getView());
        addGrayLine(firstContainer);

        room = new ItemInput(activity, firstContainer).withTitle("病房号:").init();
        room.getInput().setNumberLimit(1);
        room.getInput().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
        firstContainer.addView(room.getView());
        addGrayLine(firstContainer);

        bed = new ItemInput(activity, firstContainer).withTitle("病床号:").init();
        bed.getInput().setNumberLimit(1);
        room.getInput().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
        firstContainer.addView(bed.getView());
        addGrayLine(firstContainer);

        name = new ItemInput(activity, firstContainer).withTitle("姓名:").init();
        name.getInput().setNumberLimit(1);
        firstContainer.addView(name.getView());
        addGrayLine(firstContainer);

        age = new ItemInput(activity, firstContainer)
                .withTitle("年龄:")
                .init();
        age.getInput().setNumberLimit(1);
        room.getInput().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
        firstContainer.addView(age.getView());
        addGrayLine(firstContainer);

        sex = new ItemInput(activity, firstContainer)
                .withTitle("性别:")
                .withTvShow(true)
                .init();
        sexTv = sex.getTv();
        firstContainer.addView(sex.getView());
        sexTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectSex();
            }
        });
        addGrayLine(firstContainer);

        /** 测量值输入组 */
        /**    第二组    */
        seconfContainer.setTag(2);
        dataOne = new ItemInput(activity, seconfContainer).withTitle("餐前:").init();
        dataOne.getInput().setNumberLimit(1);
        seconfContainer.addView(dataOne.getView());
        addGrayLine(seconfContainer);

        dataTwo = new ItemInput(activity, seconfContainer).withTitle("餐后:").init();
        dataTwo.getInput().setNumberLimit(1);
        seconfContainer.addView(dataTwo.getView());

        /** 测量时间 */
        time = new ItemInput(activity, firstContainer)
                .withTitle("测量时间")
                .withTvShow(true);
        test_time = time.getTv();
        firstContainer.addView(time.getView());
        test_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new SlideDateTimePicker.Builder(activity.getSupportFragmentManager())
                        .setListener(new SlideDateTimeListener() {
                            @Override
                            public void onDateTimeSet(Date date) {
                                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                String time = formatter.format(date);
                                /** 把日期存进去 */
                                //test_time.setText(time.substring(0, 4) + "年" + time.substring(5, 7) + "月" + time.substring(8, 10) + "日");
                                test_time.setText(time);
                            }

                        })
                        .setInitialDate(new Date())
                        .setIs24HourTime(true)
                        .build()
                        .show();
            }
        });

        LinearLayout firstFather = (LinearLayout) f(R.id.firstFather);
        LinearLayout secondFather = (LinearLayout) f(R.id.secondFather);
        firstFather.addView(
                new ItemRadio(activity, firstFather)
                        .withImageDrawable(R.drawable.temperature_bg)
                        .withTvText("体温")
                        .withRadioChangeListener(new checkListener(0))
                        .init()
        );
        firstFather.addView(
                new ItemRadio(activity, firstFather)
                        .withImageDrawable(R.drawable.blood_bg)
                        .withTvText("血压")
                        .withRadioChangeListener(new checkListener(1))
                        .init()
        );
        firstFather.addView(
                new ItemRadio(activity, firstFather)
                        .withImageDrawable(R.drawable.sugar_bg)
                        .withTvText("血糖")
                        .withRadioChangeListener(new checkListener(2))
                        .init()
        );
        firstFather.addView(
                new ItemRadio(activity, firstFather)
                        .withImageDrawable(R.drawable.heart_bg)
                        .withTvText("脉搏")
                        .withRadioChangeListener(new checkListener(3))
                        .init()
        );
        secondFather.addView(
                new ItemRadio(activity, secondFather)
                        .withImageDrawable(R.drawable.breath_bg)
                        .withTvText("呼吸")
                        .withRadioChangeListener(new checkListener(4))
                        .init()
        );
        secondFather.addView(
                new ItemRadio(activity, secondFather)
                        .withImageDrawable(R.drawable.oxygen_bg)
                        .withTvText("血氧")
                        .withRadioChangeListener(new checkListener(5))
                        .init()
        );
        secondFather.addView(
                new ItemRadio(activity, secondFather)
                        .withImageDrawable(R.drawable.water_bg)
                        .withTvText("尿量")
                        .withRadioChangeListener(new checkListener(6))
                        .init()
        );
        secondFather.addView(
                new ItemRadio(activity, secondFather)
                        .withImageDrawable(R.drawable.feng_bg)
                        .withTvText("大便次数")
                        .withRadioChangeListener(new checkListener(7))
                        .init()
        );
    }

    private void selectSex() {
        AlertDialog dlg = new AlertDialog.Builder(getActivity())
                .setTitle("请选择性别")
                .setItems(new CharSequence[]{"男", "女"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 1) {
                            sexTv.setText("女");
                            dialog.cancel();
                        } else {
                            sexTv.setText("男");
                            dialog.cancel();
                        }
                    }
                })
                .create();
        dlg.show();
    }

    // 转为时间戳
    public String date2TimeStamp(String date_str, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return String.valueOf(sdf.parse(date_str).getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 数据项切换
     */
    // 目前除了血糖需要 两个输入，其他默认一个输入
    //hhc 增加一个int onSelect,方便数据显示
    private void changeDataInput(LinearLayout seconfContainer, String title, int onSelect) {
        // 固定是 secondContainer
        select = onSelect;
        dataOne = null;
        dataTwo = null;
        seconfContainer.removeAllViews(); // 先清除
        dataOne = new ItemInput(activity, seconfContainer).withTitle(title + ":").withData(data[onSelect]).init();
        dataOne.getInput().setNumberLimit(1);
        seconfContainer.addView(dataOne.getView());


        if (title.equals("餐前")) {
            addGrayLine(seconfContainer);
            dataTwo = new ItemInput(activity, seconfContainer).withTitle("餐后:").init();
            dataTwo.getInput().setNumberLimit(1);
            seconfContainer.addView(dataTwo.getView());
        } else if (title.equals("舒张压")) {
            addGrayLine(seconfContainer);
            dataTwo = new ItemInput(activity, seconfContainer).withTitle("收缩压:").init();
            dataTwo.getInput().setNumberLimit(1);
            seconfContainer.addView(dataTwo.getView());
        }
    }

    private void addGrayLine(LinearLayout Container) {
        View line = LayoutInflater.from(activity).inflate(R.layout.gray_line, Container, false);
        Container.addView(line);
    }

    /**
     * 蓝牙类
     */
    private BlueTooth blueTooth;
    private RadioButton temp = null;
    /**
     * 保存上一个打开的
     */
    //hhc
    private BluetoothSocket _socket = null; // 蓝牙通信socket
    private final static int REQUEST_CONNECT_DEVICE = 1; // 宏定义查询设备句柄
    BluetoothDevice _device = null; // 蓝牙设备
    private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter(); // 获取本地蓝牙适配器，即蓝牙设备
    boolean bThread = false;

    /**
     * 林冠宏
     */
    public class checkListener implements CompoundButton.OnCheckedChangeListener {

        private boolean isNeedBl = true;
        /**
         * 是否需要开启蓝牙
         */
        private int onSelect = -1;

        public checkListener(int onSelect) {
            this.onSelect = onSelect;
        }

        public checkListener(int onSelect, boolean isNeedBl) {
            this.onSelect = onSelect;
            this.isNeedBl = isNeedBl;
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // select=onSelect;
            String title = "";
            Log.d("zzzzz", "onCheckedChanged");

            if (isChecked) {
                Log.d("zzzzz", "isChecked");
                switch (onSelect) {
                    case 0:
                        title = "体温";
                        seconfContainer.setTag(0);
                        break;
                    case 1:
                        title = "舒张压";
                        seconfContainer.setTag(1);
                        break;
                    case 2:
                        title = "餐前";
                        seconfContainer.setTag(2);
                        break;
                    case 3:
                        title = "脉搏";
                        seconfContainer.setTag(3);
                        break;
                    case 4:
                        title = "呼吸";
                        seconfContainer.setTag(4);
                        break;
                    case 5:
                        title = "血氧";
                        seconfContainer.setTag(5);
                        break;
                    case 6:
                        title = "尿量";
                        seconfContainer.setTag(6);
                        break;
                    case 7:
                        title = "大便";
                        seconfContainer.setTag(7);
                        break;
                }
                changeDataInput(seconfContainer, title, onSelect);
                if (temp != null) { /** 如果不是 null，证明之前有点击过其他的 */
                    temp.setChecked(false);
                }
                temp = (RadioButton) buttonView;
                if (bRun) {
                    /*if(blueTooth==null){                              //hhc
                        blueTooth = new BlueTooth(activity);
                        blueTooth.withInfoBroadCast().withScanBroadCast().init();
                    }
                    if(blueTooth!=null){
                        blueTooth.open();  */     /** 打开蓝牙 */
                    if (_bluetooth.isEnabled() == false) {  //如果蓝牙服务不可用则提示
                        Toast.makeText(getActivity(), " 打开蓝牙中...", Toast.LENGTH_LONG).show();
                        return;
                    }
                    //blueTooth.startScan();  /** 开始扫描 */
                    if (_socket == null) {
                        Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class); // 跳转程序设置
                        startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); // 设置返回宏定义
                        bRun = false;
                    } else {
                        // 关闭连接socket
                        try {
                            _socket.close();
                            _socket = null;
                            bRun = false;
                        } catch (IOException e) {
                        }
                    }
                }
                // }
            } else {
                buttonView.setChecked(false);
            }
        }
    }


    Thread ReadThread = new Thread() {
        public void run() {
            byte[] buffer = new byte[1024];
            byte[] buffer1 = new byte[1024];
            int bytes;
            int n = 0;
            String readMessage = null;
            while (true) {
                try {
                    int availableBytes = is.available();
                    if (availableBytes > 0) {
                        bytes = is.read(buffer);
                        for (int i = 0; i < bytes; i++) {
                            if (buffer[i] == 0x0a) {
                                readMessage = new String(buffer1, 0, n);
                                n = 0;
                                break;
                            }
                            buffer1[n] = buffer[i];
                            n++;
                        }
                        if (readMessage != null) {
                            dataDeal(readMessage);
                            handler.sendMessage(handler.obtainMessage());
                        }
                    }
                } catch (IOException e) {
                }
            }
        }
    };

    //消息处理队列
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            //super.handleMessage(msg);
            switch (select) {
                case 0:
                    changeDataInput(seconfContainer, "体温", select);
                    break;
                case 3:
                    changeDataInput(seconfContainer, "脉搏", select);
                    break;
                case 4:
                    changeDataInput(seconfContainer, "呼吸", select);
                    break;
                case 5:
                    changeDataInput(seconfContainer, "血氧", select);
                    break;
            }
        }
    };

    //消息处理队列
    Handler handler1 = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            id.getInput().setStringText(scan_id);
            room.getInput().setStringText(scan_room);
            bed.getInput().setStringText(scan_bed);
            name.getInput().setStringText(scan_name);
            age.getInput().setStringText(scan_age);
            sexTv.setText(scan_sex);
        }
    };

    public void dataDeal(String strings) {
        String[] arrayofString = new String(strings).split("#");
        AirFlow = arrayofString[0];//呼吸
        data[4] = arrayofString[0];//呼吸
        Temperature = arrayofString[1];//体温
        data[0] = arrayofString[1];
        Pulse = arrayofString[2];//脉搏
        data[3] = arrayofString[2];
        Oxygen = arrayofString[3];//血氧
        data[5] = arrayofString[3];
    }

    public void scanDataDeal(String strings) {
        String[] arrayString = new String(strings).split("_");
        scan_id = arrayString[0];
        scan_room = arrayString[1];
        scan_bed = arrayString[2];
        scan_name = arrayString[3];
        scan_age= arrayString[4];
        scan_sex=arrayString[5];
    }


    //  扫码回调，在这里面 获取到病人 id
    private int idOfPatient = 1;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        idOfPatient = 1;
        Log.d("liangyang=",String.valueOf(requestCode));
        //hhc 接收蓝牙返回的结果
        switch (requestCode) {
            case common.CodeScan:
                Log.d("zzzzz","data "+data.getStringExtra("content"));
                String temp = data.getStringExtra("content");
                scanDataDeal(temp);
                handler1.sendMessage(handler1.obtainMessage());
                //String[] temp = (data.getStringExtra("content")).split("_");
                //Log.d("信息：","病人ID："+temp[0]+"--"+"病房号："+temp[1]
                //        +"病床号："+temp[2]+"姓名："+temp[3]+"年龄："+temp[4]);
                break;
            case REQUEST_CONNECT_DEVICE: // 连接结果，由DeviceListActivity设置返回
                // 响应返回结果
                if (resultCode == getActivity().RESULT_OK) { // 连接成功，由DeviceListActivity设置返回
                    // MAC地址，由DeviceListActivity设置返回
                    String address = data.getExtras().getString(
                            DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    // 得到蓝牙设备句柄
                    _device = _bluetooth.getRemoteDevice(address);

                    // 用服务号得到socket
                    try {
                        _socket = _device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
                    } catch (IOException e) {
                        Toast.makeText(getActivity(), "连接失败！", Toast.LENGTH_SHORT).show();
                    }

                    // 连接socket
                    try {
                        _socket.connect();
                        Toast.makeText(getActivity(), "连接" + _device.getName() + "成功！",
                                Toast.LENGTH_SHORT).show();

                    } catch (IOException e) {
                        try {
                            Toast.makeText(getActivity(), "连接失败！", Toast.LENGTH_SHORT)
                                    .show();
                            _socket.close();
                            _socket = null;
                        } catch (IOException ee) {
                            Toast.makeText(getActivity(), "连接失败！", Toast.LENGTH_SHORT)
                                    .show();
                        }

                        return;
                    }

                    // 打开接收线程
                    try {
                        is = _socket.getInputStream(); // 得到蓝牙数据输入流
                    } catch (IOException e) {
                        Toast.makeText(getActivity(), "接收数据失败！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (bThread == false) {
                        ReadThread.start();
                        bThread = true;
                    } else {
                        bRun = true;
                    }
                }
                break;
            default:
                break;
        }
    }
}
